from room import Room
from character import Character
from _xml.parser import Parser

class Club:
    def __init__(self):       
        self.__characters = []
        self.__rooms = []
        
        configuration_info = self.__get_configuration_info()
        self.__init_characters(configuration_info)
        self.__init_rooms(configuration_info)

    def __init_characters(self, config_info):        
        for p in config_info:            
            if p.get_name() == 'character':
                self.__characters.append(Character(nombre=p.get_attribute('name'),id=p.get_attribute('id')))
    
    def __init_rooms(self, config_info):        
        for e in config_info:
            if e.get_name() == 'room':
                piso = False
                if e.get_attribute('floor') == 'yes':
                    piso = True
                personaje = Character()                
                if e.get_attribute('owner') != '':
                    personaje = self.__get_character(e.get_attribute('owner'))
                self.__rooms.append(Room(nombre=e.get_attribute('name'),especial=piso,duenho=personaje,id=e.get_attribute('id')))
            elif e.get_name() == 'initial_room':
                self.__initial_room = e.get_attribute('id')                
    
    def __get_character(self, id):
        for p in self.__characters:
            if p.get_id() == id:
                return p
    
    def __get_configuration_info(self):
        f = open("../files/club.xml")
        p = Parser()
        return p.find_child_element("configuration",f)
    
    def __set_state(self,state_info):
        self.__set_rooms_state(state_info)
        self.__set_characters_state(state_info)
    
    def __set_characters_state(self, estado):        
        for c in estado.get_characters_state().items():
            id = c[0]
            per = self.__get_character(id)
            per.set_available_to_play(c[1]['juego'])
            per.set_available_to_talk(c[1]['dialogo'])                
    
    def __set_rooms_state(self,estado):
        for r in estado.get_rooms_state().items():                
            id = r[0]
            hab = self.__get_room(id)
            hab.set_available(r[1]['habilitada'])
                
    def __get_room(self, id): 
        for r in self.__rooms:
            if r.get_id() == id:
                return r           
    
    def get_rooms(self):
        return self.__rooms

    def get_initial_room(self):
        return self.__get_room(self.__initial_room)

    def set_current_state(self, estado_actual):        
        self.__set_state(estado_actual)  

